//导入数据库
const db=require('../db/index')
//导入bcryptjs
const bcrypt=require('bcryptjs')
//导入token包
const jwt=require('jsonwebtoken')
//导入全局配置文件
const config=require ('../config')

const moment=require('moment')

const { date } = require('joi')
const { resolveContent } = require('nodemailer/lib/shared')

  

//regUser
exports.regUser = (req, res) => {
   const userinfo = req.body
  const email=userinfo.email
  const code=userinfo.code
  const nowtime=moment().format('YYYY-MM-DD HH:mm:ss')
  const sql='select * from vercode where email=?'
  db.query(sql,email,(err,results)=>{
      if(err)  return res.cc(err)
      if (results.length !==1)  return res.cc("未能找到code记录")
      if(results[0].vcode!==code)
      return res.send('Verification code not correct')
      if(moment(nowtime).diff(moment(results[0].time),'minutes')>10) 
      return res.send('Verification code expired')
      const verify=require('../emailverify/code').deletecode(email)
      const sqlStr = 'select * from operator where oper_email=?'
      db.query(sqlStr, userinfo.email, (err, results) => {
        if (err) {
          return res.cc(err)
        }

        if (results.length > 0) {
          return res.cc('user is exist, please go to login')
        }
        userinfo.password=bcrypt.hashSync(userinfo.password, 10)
        const sql = 'insert into operator set ?'
        db.query(sql, {oper_email: userinfo.email, oper_password: userinfo.password }, (err, results) => {
          if (err) return res.cc(err)
          if (results.affectedRows !== 1) return res.cc('fail to register，please try again ')
          res.send({
            status:0,
            message:'register successfully' ,
      })
      })
    })})
  }


exports.resetpassword= (req,res)=>{
  const userinfo=req.body
  const email=userinfo.email
  const code=userinfo.code
  const nowtime=moment().format('YYYY-MM-DD HH:mm:ss')
  const sql='select * from vercode where email=?'
  db.query(sql,email,(err,results)=>{
      if(err)  return res.cc(err)
      if (results.length !==1)  return res.cc("未能找到code记录")
       if(results[0].vcode!==code)
       return res.send('Verification code not correct')
       if(moment(nowtime).diff(moment(results[0].time),'minutes')>10) 
       return res.send('Verification code expired')
        const verify=require('../emailverify/code').deletecode(email)
    const sql='select * from operator where oper_email=?'
    db.query(sql,userinfo.email,(err,results)=>{
      if(err) return res.cc(err)
      if(results.length !==1) return res.cc("user is not exist")
      const sql='update operator set oper_password=? where oper_email=?'
      //encrypt
      const password=bcrypt.hashSync(userinfo.password,10)
      db.query(sql,[password,userinfo.email],(err,results)=>{
          if(err) return res.cc(err)
          if(results.affectedRows!==1) return res.cc('failed to reset password')
          res.send({
            status:0,
            message:'reset successfully' ,
        })
      })
    })
  })
   
}


exports.login= (req,res)=>{
  const userinfo=req.body
  const email=userinfo.email
  const code=userinfo.code
  const nowtime=moment().format('YYYY-MM-DD HH:mm:ss')
  console.log(nowtime)
  const sql='select * from vercode where email=?'
  db.query(sql,email,(err,results)=>{
      if(err)  return res.cc(err)
      if (results.length !==1)  return res.cc("未能找到code记录")

       if(results[0].vcode!==code)
       return res.send('Verification code not correct')
       if(moment(nowtime).diff(moment(results[0].time),'minutes')>10) 
       return res.send('Verification code expired')
       const verify=require('../emailverify/code').deletecode(email)
       const sql = 'select * from operator where oper_email=?'
       db.query(sql,userinfo.email,(err,results)=>{
       if(err) return res.cc(err)
       if(results.length !==1) return res.cc('user not exist')
       const compareResult=bcrypt.compareSync(userinfo.password, results[0].oper_password)
       if(!compareResult) return res.cc('password error,failed to login')
       const user={...results[0],oper_password:'',hiredate:''}
       //generate token string
       const tokenStr=jwt.sign(user,config.jwtSecretKey,{expiresIn:'10h'})
       console.log("发送token")
       res.send(
           {
               status:0,
               message:'login successfully',
               token:'Bearer '+tokenStr,
           }
       )})
      }  
  )
 
}

